/**
 * API客户端 - 统一的API调用工具
 * 
 * 自动处理认证、错误处理和响应格式化
 */

// 获取认证token
function getAuthToken(): string {
  // 客户端环境：从localStorage或cookie获取
  if (typeof window !== 'undefined') {
    // 统一使用auth-token，不再区分管理员和普通用户token
    const userToken = localStorage.getItem('auth-token')
    if (userToken) {
      console.log('从localStorage获取到auth-token')
      return userToken
    }

    // 尝试从cookie获取token
    const cookieToken = getCookieValue('auth-token')
    if (cookieToken) {
      console.log('从cookie获取到auth-token')
      return cookieToken
    }
    
    console.log('未找到有效的auth-token')
  }

  // 不再使用开发环境硬编码token，依赖正常的认证流程
  return ''
}

// 从cookie获取值的辅助函数（保留但不用于认证）
function getCookieValue(name: string): string | null {
  if (typeof document === 'undefined') return null

  const value = `; ${document.cookie}`
  const parts = value.split(`; ${name}=`)
  if (parts.length === 2) {
    return parts.pop()?.split(';').shift() || null
  }
  return null
}

// 创建认证头
function getAuthHeaders(): Record<string, string> {
  const token = getAuthToken()
  const headers: Record<string, string> = {
    'Content-Type': 'application/json'
  }
  
  if (token) {
    headers['Authorization'] = `Bearer ${token}`
    console.log('设置Authorization头')
  } else {
    console.log('未设置Authorization头，因为没有找到token')
  }
  
  return headers
}

// API响应类型
interface ApiResponse<T = any> {
  success: boolean
  data?: T
  error?: string
  message?: string
}

// API客户端类
export class ApiClient {
  private baseUrl: string

  constructor(baseUrl = '') {
    this.baseUrl = baseUrl
  }

  // GET请求
  async get<T = any>(endpoint: string): Promise<ApiResponse<T>> {
    try {
      const response = await fetch(`${this.baseUrl}${endpoint}`, {
        method: 'GET',
        headers: getAuthHeaders(),
        credentials: 'include' // 确保发送 cookies
      })

      const data = await response.json()
      
      if (!response.ok) {
        return {
          success: false,
          error: data.error || `HTTP ${response.status}`,
          data: data
        }
      }

      return {
        success: true,
        data: data.data || data,
        message: data.message
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '网络错误'
      }
    }
  }

  // POST请求
  async post<T = any>(endpoint: string, body?: any): Promise<ApiResponse<T>> {
    try {
      const response = await fetch(`${this.baseUrl}${endpoint}`, {
        method: 'POST',
        headers: getAuthHeaders(),
        credentials: 'include', // 确保发送 cookies
        body: body ? JSON.stringify(body) : undefined
      })

      const data = await response.json()
      
      if (!response.ok) {
        return {
          success: false,
          error: data.error || `HTTP ${response.status}`,
          data: data
        }
      }

      return {
        success: true,
        data: data.data || data,
        message: data.message
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '网络错误'
      }
    }
  }

  // PUT请求
  async put<T = any>(endpoint: string, body?: any): Promise<ApiResponse<T>> {
    try {
      const response = await fetch(`${this.baseUrl}${endpoint}`, {
        method: 'PUT',
        headers: getAuthHeaders(),
        credentials: 'include', // 确保发送 cookies
        body: body ? JSON.stringify(body) : undefined
      })

      const data = await response.json()
      
      if (!response.ok) {
        return {
          success: false,
          error: data.error || `HTTP ${response.status}`,
          data: data
        }
      }

      return {
        success: true,
        data: data.data || data,
        message: data.message
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '网络错误'
      }
    }
  }

  // PATCH请求
  async patch<T = any>(endpoint: string, body?: any): Promise<ApiResponse<T>> {
    try {
      const response = await fetch(`${this.baseUrl}${endpoint}`, {
        method: 'PATCH',
        headers: getAuthHeaders(),
        credentials: 'include', // 确保发送 cookies
        body: body ? JSON.stringify(body) : undefined
      })

      const data = await response.json()
      
      if (!response.ok) {
        return {
          success: false,
          error: data.error || `HTTP ${response.status}`,
          data: data
        }
      }

      return {
        success: true,
        data: data.data || data,
        message: data.message
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '网络错误'
      }
    }
  }

  // DELETE请求
  async delete<T = any>(endpoint: string): Promise<ApiResponse<T>> {
    try {
      const response = await fetch(`${this.baseUrl}${endpoint}`, {
        method: 'DELETE',
        headers: getAuthHeaders(),
        credentials: 'include' // 确保发送 cookies
      })

      const data = await response.json()
      
      if (!response.ok) {
        return {
          success: false,
          error: data.error || `HTTP ${response.status}`,
          data: data
        }
      }

      return {
        success: true,
        data: data.data || data,
        message: data.message
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '网络错误'
      }
    }
  }
}

// 默认API客户端实例
export const apiClient = new ApiClient()

// 管理员API客户端
export const adminApi = {
  // 获取工具列表
  getTools: () => apiClient.get('/api/admin/tools'),

  // 获取用户列表
  getUsers: () => apiClient.get('/api/admin/users'),

  // 获取评价列表
  getReviews: () => apiClient.get('/api/admin/reviews'),

  // 获取收藏列表
  getFavorites: () => apiClient.get('/api/admin/favorites'),

  // 切换工具状态
  toggleTool: (toolId: string, isDeployed: boolean) =>
    apiClient.patch(`/api/admin/tools/${toolId}/toggle`, { isDeployed }),

  // 更新工具信息
  updateTool: (toolId: string, data: { title: string; description: string; url: string; categoryId: string; status: string }) =>
    apiClient.patch(`/api/admin/tools/${toolId}`, data),

  // 删除工具
  deleteTool: (toolId: string) =>
    apiClient.delete(`/api/admin/tools/${toolId}`),

  // 重新部署工具
  redeployTool: (toolId: string) =>
    apiClient.post(`/api/admin/tools/${toolId}/redeploy`),

  // 审核通过工具
  approveTool: (toolId: string) =>
    apiClient.post(`/api/admin/tools/${toolId}/approve`),

  // 审核拒绝工具
  rejectTool: (toolId: string) =>
    apiClient.post(`/api/admin/tools/${toolId}/reject`),

  // 上传工具
  uploadTool: (formData: FormData) =>
    apiClient.post('/api/admin/tools/upload', formData, {
      'Content-Type': 'multipart/form-data'
    }),
}

// 工具API客户端
export const toolsApi = {
  // 获取工具列表
  getTools: (params?: Record<string, string>) => {
    const query = params ? '?' + new URLSearchParams(params).toString() : ''
    return apiClient.get(`/api/tools${query}`)
  },
  
  // 获取工具详情
  getTool: (toolId: string) => 
    apiClient.get(`/api/tools/${toolId}`),
  
  // 创建工具
  createTool: (toolData: any) => 
    apiClient.post('/api/tools', toolData),
  
  // 获取工具评价
  getReviews: (toolId: string) => 
    apiClient.get(`/api/tools/${toolId}/reviews`),
  
  // 添加评价
  addReview: (toolId: string, reviewData: any) => 
    apiClient.post(`/api/tools/${toolId}/reviews`, reviewData),
}

// 用户API客户端
export const userApi = {
  // 获取用户信息
  getProfile: () => apiClient.get('/api/user/profile'),
  
  // 更新用户信息
  updateProfile: (userData: any) => 
    apiClient.put('/api/user/profile', userData),
  
  // 获取用户收藏
  getFavorites: () => apiClient.get('/api/user/favorites'),
  
  // 添加收藏
  addFavorite: (toolId: string) => 
    apiClient.post('/api/user/favorites', { toolId }),
  
  // 移除收藏
  removeFavorite: (toolId: string) => 
    apiClient.delete(`/api/user/favorites/${toolId}`),
}
